<template>
	<view class="content">
		<view class="navbar" :style="{position:headerPosition,top:headerTop}">
			<view class="nav-item" :class="{current: filterIndex === 0}" @click="tabClick(0)">
				商品
			</view>
			<view class="nav-item" :class="{current: filterIndex === 1}" @click="tabClick(1)">
				品牌
			</view>
			<!-- <view class="nav-item" :class="{current: filterIndex === 2}" @click="tabClick(2)">
				店铺
			</view> -->

		</view>
		<!-- 历史搜索 -->
		<view class="HistorySearch" v-if="isHistory==true" :style="{top:headerTop}">
			<view class="HistorySearch_tittel">
				<text class="tittelL">历史搜索</text>
				<text class="img_dell">
					<image @click="clearHistoryItems" src="../../static/img/4/4-5.png" mode="aspectFill"></image>
				</text>
			</view>
			<view class="HistorySearch_main" v-if="searchHistoryList.length">
				<text class="HistorySearch_item" @click="getkey(Item)" v-for="Item in searchHistoryList" :key="Item.id">{{Item}}</text>
			</view>
			<view class="space"></view>
			<view class="HistorySearch_tittel">
				<text class="tittelL">热门搜索</text>
			</view>
			<view class="HistorySearch_main">
				<text class="HistorySearch_item" @click="getkey(item.name)" v-for="item in hotList" :key="item.index">{{item.name}}</text>

			</view>

		</view>
		<!-- 竖向商品 -->
		<list :goodsList="goodsList" v-if="filterIndex === 0&& listheng===0"></list>

		<!-- 横向商品 -->
		<goodsH v-if="filterIndex === 0&& listheng===1" :goodsList="goodsList"></goodsH>

		<!-- 品牌 -->
		<uni-indexed-list :options="list" :showSelect="true" @click="bindClick" v-if="filterIndex === 1"></uni-indexed-list>

		<!-- 店铺 -->
		<!-- <uni-indexed-list :options="list" :showSelect="true" @click="bindClick"  v-if="filterIndex === 2"></uni-indexed-list> -->


		<uni-load-more :status="loadingType" ></uni-load-more>

		<view class="cate-mask" :class="cateMaskState===0 ? 'none' : cateMaskState===1 ? 'show' : ''" @click="toggleCateMask">
			<view class="cate-content" @click.stop.prevent="stopPrevent" @touchmove.stop.prevent="stopPrevent">
				<scroll-view scroll-y class="cate-list">
					<view v-for="item in cateList" :key="item.id">
						<view class="cate-item b-b two">{{item.name}}</view>
						<view v-for="tItem in item.child" :key="tItem.id" class="cate-item b-b" :class="{active: tItem.id==cateId}"
						 @click="changeCate(tItem)">
							{{tItem.name}}
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
		<!-- 暂无搜索记录 -->
		<view class="no-record" v-if="goodsList.length == 0">
			<view class="">
				<image src="../../static/img/4/4-6.png" mode=""></image>
			</view>
			<view class="">
				<!-- <text>暂时还没有哟~~~</text> -->
			</view>
		</view>
	</view>
</template>

<script>
	import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue';
	import listOther from '@/components/list/listOther.vue';
	import list from '@/components/list/list.vue';
	import goodsH from '@/components/search/goods_heng.vue';
	import uniIndexedList from "@/components/uni-indexed-list/uni-indexed-list.vue"
	export default {
		components: {
			uniLoadMore,
			listOther,
			goodsH,
			list,
			uniIndexedList,

		},
		data() {
			return {
				isHistory: true,
				listheng: 0,
				cateMaskState: 0, //分类面板展开状态
				headerPosition: "fixed",
				headerTop: "44px",
				loadingType: 'more', //加载更多状态
				filterIndex: 0,
				cateId: 0, //已选三级分类id
				priceOrder: 0, //1 价格从低到高 2价格从高到低
				cateList: [],
				goodsList: [],
				record: false,
				key: '',
				searchHistoryList: [],
				// 标记显示搜索历史
				showFlag: false,
				loadShow: false,
				list: [],
				hotList: [],
				pinpaiList: [],
				shop_id:'',
				goodsPage:1

			};
		},
		onShow() {
			this.list = []
			// this.getlist()
			// #ifdef H5
			// this.headerTop = document.getElementsByTagName('uni-page-head')[0].offsetHeight + 'px';
			// #endif

			// this.loadCateList(options.fid, options.sid);
			this.loadData();
			this.searchHistoryList = this.$SysCache.get('historyItems')

			console.log(this.$SysCache.get('historyItems'))

			var that = this
			that.hot()

			this.$Request.post4(
				this.$api.httpApi.goods.goodsBrand, {
						"keyword": that.key
					}
			).then(res => {
				if (res.code == 1) {
					// for(var i = 0;i<6 ; i++){
					// 	res.data.push(res.data[i])
					// }

					res.data.forEach(item => {
						var data = {}
						// that.getpy(item.name)
						that.$set(data, "letter", that.getpy(item.brand_name))
						that.$set(data, "data", [])
						data.data.push(item)

						that.list.push(data)

					})
					// for(var i = 0;i<that.list.length ; i++){
					// 	console.log(that.list[i].data[0])
					// 	if(that.list[i].letter = that.list[i+1].letter){
					// 		that.list[i].data.push(that.list[i+1].data[0])
					// 		// that.list[i+1] = ''
					// 	}
					// }
					// this.unique(this.list.letter)

				}

			})

		},

		onLoad(options) {
			this.cateId = options.tid;
			this.shop_id = options.shop_id
		},
		onPageScroll(e) {
			//兼容iOS端下拉时顶部漂移
			if (e.scrollTop >= 0) {
				this.headerPosition = "fixed";
			} else {
				this.headerPosition = "absolute";
			}
		},
		//下拉刷新
		onPullDownRefresh() {
			this.loadData('refresh');
		},
		//加载更多
		onReachBottom() {
			// this.loadData();
			if(!this.record){
				this.goodssearch()
				this.getlist()
			}
			
		},

		methods: {
			// getpy(name) {
			// 	return this.$api.pinyin.chineseToPinYin(name).slice(0, 1)
			// },
			//去重
			unique(arr) { // 根据唯一标识no来对数组进行过滤
				const res = new Map(); //定义常量 res,值为一个Map对象实例
				//返回arr数组过滤后的结果，结果为一个数组   过滤条件是，如果res中没有某个键，就设置这个键的值为1
				return arr.filter((arr) => !res.has(arr.no) && res.set(arr.no, 1))
			},


			getlist() {
				let that = this;
				this.$Request.post4(
					this.$api.httpApi.goods.goodsBrand, {
						"keyword": that.key,
						shop_id: that.shop_id
					}
				).then(res => {
					console.log(res.data)
					if (res.code == 1) {
						that.list = []
						res.data.forEach(item => {
							var data = {}
							// that.getpy(item.name)
							that.$set(data, "letter", that.getpy(item.brand_name))
							that.$set(data, "data", [])
							data.data.push(item)
							// data.data.push(item.adImage)
							that.list.push(data)

						})
						console.log(that.list)

					}

				})

			},


			getkey(key) {
				console.log(key)
				document.getElementsByClassName('uni-input-input')[0].value = key
				this.key = key
				this.isHistory = false
				this.goodsPage = 1
				this.goodssearch()
				this.getlist()



			},
			//汉字转化拼音取首字母
			getpy(name) {
				return this.$api.pinyin.chineseToPinYin(name).slice(0, 1)
			},
			//去重
			// unique(arr) { // 根据唯一标识no来对数组进行过滤
			// 　　const res = new Map();  //定义常量 res,值为一个Map对象实例
			// 　　//返回arr数组过滤后的结果，结果为一个数组   过滤条件是，如果res中没有某个键，就设置这个键的值为1
			// 　　return arr.filter((arr) => !res.has(arr.no) && res.set(arr.no, 1)) 
			//     },
			showHistory() {
				if (this.searchHistoryList.length > 0) {
					this.showFlag = true
				}
			},
			// 清空历史记录
			clearHistoryItems() {
				// localStorage.removeItem('historyItems')
				this.$SysCache.remove('historyItems')
				this.searchHistoryList = []
				this.showFlag = false
			},
			appendKeywords(value) {
				var that = this
				/**
				 * 1.已经有的关键词不再添加
				 * 2.添加到数组的首位，若超出10个则删除最后一个
				 * 3.添加到缓存
				 */
				var appendFlag = true
				if (this.searchHistoryList !== null && this.searchHistoryList !== undefined && this.searchHistoryList.length > 0) {
					this.searchHistoryList.forEach(function(currentValue, index) {
						if (currentValue === value) {
							appendFlag = false
							return
						}
					})
					// 判断-添加
					if (appendFlag === true) {
						// 长度判断
						if (this.searchHistoryList.length >= 10) {
							this.searchHistoryList.unshift(value)
							this.searchHistoryList.pop()
						} else {
							this.searchHistoryList.unshift(value)
						}

						that.$SysCache.put('historyItems', that.searchHistoryList)
						// localStorage.setItem('historyItems', JSON.stringify(this.searchHistoryList))
					}
				} else {
					this.searchHistoryList = []
					this.searchHistoryList.push(value)
					that.$SysCache.put('historyItems', that.searchHistoryList)
				}
			},
			searchByHistoryKeyWord(item) {
				this.loadTip = ''
				this.queryData.inputInfo = item
				// 查询
				fetchGetDataByKeyWord(item).then(response => {
					// 查询赋值
					this.dataList = response.data.body.data
					if (this.dataList.length === 0) {
						this.loadTip = '没有符合条件数据'
						this.showHistory()
					} else {
						this.loadTip = ''
						this.showFlag = false
					}
				})
			},


			//加载商品 ，带下拉刷新和上滑加载
			async loadData(type = 'add', loading) {
				//没有更多直接返回
				if (type === 'add') {
					if (this.loadingType === 'nomore') {
						return;
					}
					// this.loadingType = 'loading';
				} else {
					this.loadingType = 'more'
				}

				// let goodsList = await this.$api.json('goodsList');
				if (type === 'refresh') {
					this.goodsList = [];
				}
				//筛选，测试数据直接前端筛选了
				if (this.filterIndex === 1) {
					// goodsList.sort((a, b) => b.sales - a.sales)
				}
				if (this.filterIndex === 2) {
					// goodsList.sort((a, b) => {
					// 	if (this.priceOrder == 1) {
					// 		return a.price - b.price;
					// 	}
					// 	return b.price - a.price;
					// })
				}

				// this.goodsList = this.goodsList.concat(goodsList);

				//判断是否还有下一页，有是more  没有是nomore(测试数据判断大于20就没有了)
				this.loadingType = this.goodsList.length > 20 ? 'nomore' : 'more';
				
				if (type === 'refresh') {
					if (loading == 1) {
						uni.hideLoading()
					} else {
						uni.stopPullDownRefresh();
					}
				}
			},
			//筛选点击
			tabClick(index) {
				if (this.filterIndex === index && index !== 2) {
					return;
				}
				this.filterIndex = index;
				if (index === 2) {
					this.priceOrder = this.priceOrder === 1 ? 2 : 1;
				} else {
					this.priceOrder = 0;
				}
				uni.pageScrollTo({
					duration: 300,
					scrollTop: 0
				})
				// this.loadData('refresh', 1);
				// uni.showLoading({
				// 	title: '正在加载'
				// })
			},
			//显示分类面板
			toggleCateMask(type) {
				let timer = type === 'show' ? 10 : 300;
				let state = type === 'show' ? 1 : 0;
				this.cateMaskState = 2;
				setTimeout(() => {
					this.cateMaskState = state;
				}, timer)
			},
			//分类点击
			changeCate(item) {
				this.cateId = item.id;
				this.toggleCateMask();
				uni.pageScrollTo({
					duration: 300,
					scrollTop: 0
				})
				this.loadData('refresh', 1);
				uni.showLoading({
					title: '正在加载'
				})
			},
			onKeyUserNameInput: function(event) {
				this.key = event.detail

			},
			// 商品搜索
			goodssearch() {
				let that = this;
				that.$Request.post(
					that.$api.httpApi.search.search + "&token=" + this.$SysCache.get('token'), {
						queryCondition: {
							order: [{
								fieldname: "iOrder",
								direction: "asc"
							}],
							pageindex: 1,
							pagesize: 20,
							where: [{
								fieldname: "keyword",
								valuefrom: this.key
							},{
								fieldname: "shop_id",
								valuefrom: this.shop_id
							}]
						}
					}
				).then(res => {
					if (res.code == 200) {
						console.log(res)
						that.goodsList = res.data.data
						if(res.data.data.length == 0){
							that.record  = true
						}else{
							that.record  = false
						}
					}
				})
				// let sendData = {
				// 	keyword: that.key,
				// 	shop_id: that.shop_id,
				// 	pageIndex: this.goodsPage,
				// 	pageSize: 20
				// }

				// this.$Request.post4(
				// 	this.$api.httpApi.home.bandGoods, sendData
				// ).then(res => {
				// 	console.log(res.data)
				// 	if (res.code == 1) {
				// 		console.log(res)
				// 		that.goodsList = that.goodsList.concat(res.data.recordList)
				// 		that.goodsPage++
				// 		if (res.data.endPageIndex < that.goodsPage) {
				// 			that.record = true
				// 			that.loadingType = "nomore"
				// 		} else {
				// 			that.record = false
				// 		}

				// 	}

				// })


			},
			// 品牌搜索
			brandsearch() {
				let that = this;
				console.log(that.key)
				that.$Request.post(
					that.$api.httpApi.search.search + "&token=" + this.$SysCache.get('token'), {
						queryCondition: {
							order: [{
								fieldname: "iOrder",
								direction: "asc"
							}],
							pageindex: 1,
							pagesize: 12,
							where: [{
								fieldname: "keyword",
								valuefrom: this.key
							}]
						}
					}
				).then(res => {
					if (res.code == 200) {
						console.log(res)
						that.pinpaiList = res.data.data
					}
				})
			},
			// 店铺搜索



			// 热门
			hot() {
				let that = this;
				that.$Request.post(
					that.$api.httpApi.search.hot + "&token=" + this.$SysCache.get('token'), {
						terminaltype: "WECHAT"
					}
				).then(res => {
					if (res.code == 200) {
						console.log(res.data)
						that.hotList = res.data.pkword
					}
				})
			},


			//详情
			navToDetailPage(item) {
				//测试数据没有写id，用title代替
				let id = item.id;
				uni.navigateTo({
					url: `/pages/detail/index?id=${id}`
				})
			},
			stopPrevent() {}
		},
		onNavigationBarButtonTap(e) {
			console.log(e)
			if (this.listheng == 0) {
				// e.text = "<image src='static/img/4/4-2.png' width='21' height='21' style='margin-right:5px'></image>"


				this.listheng = 1

			} else {
				this.listheng = 0

			}


		},
		onNavigationBarSearchInputChanged: async function(e) {

			this.key = e.text

			this.isHistory = false
			console.log(e.text)


			// uni.showToast({
			//     title: '搜索',
			//     duration: 2000
			//             });

		},

		onNavigationBarSearchInputConfirmed: async function(e) {
			var that = this
			this.isHistory = false
			console.log(e)
			this.goodsList = []
			this.appendKeywords(that.key)
			this.goodssearch()
			this.getlist()
			e.text = ''
		}

	}
</script>

<style lang="scss" scoped>
	.uni-input-input {
		color: #fff;
	}

	
	.content {
		background: $page-color-base;
		top: 44px;
		// position: fixed;
		width: 100%;
		height: 100%;
		overflow-y: scroll;
		-webkit-overflow-scrolling: touch;
	}

	.content {
		padding-top: 96upx;
	}

	.navbar {
		position: fixed;
		left: 0;
		top: 44px;
		display: flex;
		width: 100%;
		height: 80upx;
		background: #fff;
		box-shadow: 0 2upx 10upx rgba(0, 0, 0, .06);
		z-index: 10;

		.nav-item {
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 100%;
			font-size: 30upx;
			color: $font-color-dark;
			position: relative;

			&.current {
				color: #4DC897;

				&:after {
					content: '';
					position: absolute;
					left: 50%;
					bottom: 0;
					transform: translateX(-50%);
					width: 80upx;
					height: 0;
					border-bottom: 4upx solid #4DC897;
				}
			}
		}

		.p-box {
			display: flex;
			flex-direction: column;

			.yticon {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 30upx;
				height: 14upx;
				line-height: 1;
				margin-left: 4upx;
				font-size: 26upx;
				color: #888;

				&.active {
					color: $base-color;
				}
			}

			.xia {
				transform: scaleY(-1);
			}
		}

		.cate-item {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 100%;
			width: 80upx;
			position: relative;
			font-size: 44upx;

			&:after {
				content: '';
				position: absolute;
				left: 0;
				top: 50%;
				transform: translateY(-50%);
				border-left: 1px solid #ddd;
				width: 0;
				height: 36upx;
			}
		}
	}

	/* 分类 */
	.cate-mask {
		position: fixed;
		left: 0;
		top: var(--window-top);
		bottom: 0;
		width: 100%;
		background: rgba(0, 0, 0, 0);
		z-index: 95;
		transition: .3s;

		.cate-content {
			width: 630upx;
			height: 100%;
			background: #fff;
			float: right;
			transform: translateX(100%);
			transition: .3s;
		}

		&.none {
			display: none;
		}

		&.show {
			background: rgba(0, 0, 0, .4);

			.cate-content {
				transform: translateX(0);
			}
		}
	}

	.cate-list {
		display: flex;
		flex-direction: column;
		height: 100%;

		.cate-item {
			display: flex;
			align-items: center;
			height: 90upx;
			padding-left: 30upx;
			font-size: 28upx;
			color: #555;
			position: relative;
		}

		.two {
			height: 64upx;
			color: #303133;
			font-size: 30upx;
			background: #f8f8f8;
		}

		.active {
			color: $base-color;
		}
	}

	/* 商品列表 */
	.goods-list {
		display: flex;
		flex-wrap: wrap;
		padding: 0 30upx;
		background: #F9F9F9;

		.goods-item {
			display: flex;
			flex-direction: column;
			width: 48%;
			padding-bottom: 40upx;
			box-shadow: 0px 0px 15px 0px rgba(0, 0, 0, 0.08);
			margin-top: 25upx;
			background: #fff;

			&:nth-child(2n+1) {
				margin-right: 4%;
			}
		}

		.image-wrapper {
			width: 100%;
			height: 330upx;
			border-radius: 3px;
			overflow: hidden;

			image {
				width: 100%;
				height: 100%;
				opacity: 1;
			}
		}

		.title {
			font-size: 28upx;
			color: #444444;
			line-height: 80upx;
			padding: 0 12upx;
		}

		.price-box {
			// display: flex;
			align-items: center;
			justify-content: space-between;
			padding-right: 10upx;
			font-size: 24upx;
			width: 80%;
			color: #999999;
		}

		.price {
			padding: 0 12upx;
			font-size: $font-lg;
			color: $uni-color-primary;
			line-height: 1;

			&:before {
				content: '￥';
				font-size: 26upx;
			}
		}

		.shoucang_box {
			margin-top: -30upx;
		}

		.shoucang {
			width: 38upx;
			height: 33upx;
		}

		.font_box {
			display: flex;
			justify-content: space-between;
			padding-right: 10upx;
		}
	}

	.HistorySearch {
		width: 100%;
		position: fixed;
		background: #fff;
		left: 0;
		z-index: 100;
		.space{
			height: 0.5rem;
			background: #f8f8f8;
		}
		// display: none;

		.HistorySearch_tittel {
			display: flex;
			padding: 20upx;
			justify-content: space-between;

		}

		.tittelL {
			font-size: 28upx;
			color: #000;
		}

		.img_dell image {
			width: 29upx;
			height: 28upx;
			vertical-align: middle;
		}

	}

	.HistorySearch_main {
		display: flex;
		flex-wrap: wrap;
		padding: 0 30upx;

		.HistorySearch_item {
			padding: 0 32upx;
			border-radius: 5upx;
			color: #6D6D6D;
			font-size: 22upx;
			// background: #F7F7F7;
			margin: 0 25upx 20upx 0;
			border: 1upx solid #999;
		}
	}

	.uni-input-input {
		color: #fff;
	}

	.no-record image {
		width: 349upx;
		height: 288upx;
		margin: 60upx auto;
	}

	.no-record {
		text-align: center;
		position: relative;
		top: 25%;
	}

	.no-record text {
		text-align: center;
		color: #616161;
	}

	.uni-indexed-list {
		top: 80upx;
	}

	.toast-message {
		font-size: 28upx !important;
	}

	.noticeError {
		font-size: 28upx !important;
	}
</style>
